package com.example.erp;

import java.util.Map;

import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.ListToolsResult;
import io.modelcontextprotocol.spec.McpSchema.TextContent;

/**
 * 使用sse传输，需要单独启动一个应用作为MCP服务器。
 */
public class ClientSseWebmvc {

	private static final String MCP_SERVER_BASE_URI = "http://localhost:8081"; // /mcp-server
	private static final String SSE_ENDPOINT = "/sse"; // 默认/sse，可以不指定，服务器通过 /sse 发送消息给客户端

	public static void main(String[] args) {
		HttpClientSseClientTransport transport = HttpClientSseClientTransport.builder(MCP_SERVER_BASE_URI)
				.sseEndpoint(SSE_ENDPOINT)			
				.build();

		try (McpSyncClient client = McpClient.sync(transport).build()) {

			client.initialize();

			// 调用工具示例
			ListToolsResult toolsList = client.listTools();
			System.out.println("1-可用的工具集：" + toolsList);
			System.err.println("================================");

			CallToolResult sumResult = client.callTool(new CallToolRequest("add", Map.of("a", 1, "b", 2)));
			System.out.println("2-加法计算：1+2 = " + ((TextContent) sumResult.content().get(0)).text());
			System.err.println("================================");

			CallToolResult currentTimResult = client.callTool(new CallToolRequest("getCurrentTime", Map.of()));
			System.out.println("3-当前时间：" + ((TextContent) currentTimResult.content().get(0)).text());
			System.err.println("================================");

			// 获取北京的天气预报
			CallToolResult weatherForecastResult = client.callTool(new CallToolRequest("getWeatherForecastByLocation",
					Map.of("latitude", "39.9042", "longitude", "116.4074")));
			//System.out.println("4-北京天气预报: " + weatherForecastResult);
			System.out.println("4-北京天气预报: " + ((TextContent) weatherForecastResult.content().get(0)).text());
			System.err.println("================================");

			// 获取北京的空气质量信息
			CallToolResult airQualityResult = client.callTool(new CallToolRequest("getAirQuality", 
					Map.of("latitude", "39.9042", "longitude", "116.4074")));
			//System.out.println("5-北京空气质量: " + airQualityResult);
			System.out.println("5-北京空气质量: " + ((TextContent) airQualityResult.content().get(0)).text());

			// close
			client.closeGracefully();
		}
	}

}
